<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>{{ isLogin ? '欢迎回来' : '创建账号' }}</h2>
        <p class="subtitle">{{ isLogin ? '请登录您的账号' : '请填写以下信息注册' }}</p>
      </div>
      
      <el-form 
        :model="formData" 
        :rules="rules" 
        ref="formRef"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="formData.username" 
            :placeholder="isLogin ? '请输入用户名' : '请设置用户名'"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            :placeholder="isLogin ? '请输入密码' : '请设置密码'"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <template v-if="!isLogin">
          <el-form-item prop="email">
            <el-input
              v-model="formData.email"
              placeholder="请输入邮箱"
            >
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="verificationCode">
            <div class="verification-code">
              <el-input
                v-model="formData.verificationCode"
                placeholder="请输入验证码"
              >
                <template #prefix>
                  <el-icon><Key /></el-icon>
                </template>
              </el-input>
              <el-button 
                type="primary" 
                :disabled="cooldown > 0"
                @click="sendVerificationCode"
              >
                {{ cooldown > 0 ? `${cooldown}s后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="loading"
            class="submit-btn"
          >
            {{ isLogin ? '登录' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="form-footer">
        <span @click="toggleMode" class="toggle-mode">
          {{ isLogin ? '没有账号？立即注册' : '已有账号？立即登录' }}
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "../store/user";
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";
import { User, Lock, Message, Key } from '@element-plus/icons-vue'

const router = useRouter();
const userStore = useUserStore();
const formRef = ref<FormInstance>();
const loading = ref(false);
const isLogin = ref(true);
const cooldown = ref(0);

const formData = reactive({
  username: "",
  password: "",
  email: "",
  verificationCode: ""
});

const rules = computed(() => ({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度应在2-20个字符之间", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 3, max: 20, message: "密码长度应在3-20个字符之间", trigger: "blur" }
  ],
  email: isLogin.value ? [] : [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
  ],
  verificationCode: isLogin.value ? [] : [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码长度应为6位", trigger: "blur" }
  ]
}));

const toggleMode = () => {
  isLogin.value = !isLogin.value;
  formRef.value?.resetFields();
};

const startCooldown = () => {
  cooldown.value = 60;
  const timer = setInterval(() => {
    cooldown.value--;
    if (cooldown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

const sendVerificationCode = async () => {
  try {
    // 验证邮箱格式
    const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    
    if (!formData.email) {
      ElMessage.warning("请先输入邮箱");
      return;
    }
    
    if (!emailRegex.test(formData.email)) {
      ElMessage.warning("请输入正确的邮箱格式");
      return;
    }

    // 禁用按钮，防止重复点击
    if (cooldown.value > 0) return;
    
    await userStore.sendVerificationCode(formData.email);
    startCooldown();
  } catch (error) {
    // 错误已在store中处理
    console.error('验证码发送失败:', error);
  }
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        if (isLogin.value) {
          // TODO: 实现登录逻辑
          await userStore.login(formData.username, formData.password);
          ElMessage.success("登录成功");
          router.push("/");
        } else {
          // TODO: 实现注册逻辑
          await userStore.register(formData);
          ElMessage.success("注册成功");
          isLogin.value = true;
        }
      } catch (error: any) {
        ElMessage.error(error.message || (isLogin.value ? "登录失败" : "注册失败"));
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  overflow: auto;
}

.login-box {
  width: 100%;
  max-width: 420px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 8px;
}

.subtitle {
  color: #666;
  font-size: 14px;
}

.login-form {
  margin-bottom: 20px;
}

.verification-code {
  display: flex;
  gap: 12px;
}

.verification-code .el-input {
  flex: 1;
}

.verification-code .el-button {
  width: 120px;
}

.submit-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: transform 0.2s;
}

.submit-btn:hover {
  transform: translateY(-1px);
}

.form-footer {
  text-align: center;
  margin-top: 20px;
}

.toggle-mode {
  color: #667eea;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.2s;
}

.toggle-mode:hover {
  color: #764ba2;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 8px;
}

:deep(.el-input__inner) {
  height: 44px;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}
</style>
